#include "stdafx.h"
#include "script.h"
#include "javascript.h"
#include "pythonscript.h"

namespace gtl
{

namespace skins
{

gtl::script* script::m_jscript = NULL;
gtl::script* script::m_pyscript = NULL;
int script::m_counter = 0;

script::script()
{
	++m_counter;
}

script::~script()
{
	if(--m_counter == 0)
	{
		if(m_jscript != NULL)
			delete m_jscript;
		if(m_pyscript != NULL)
			delete m_pyscript;
	}
}

unsigned int script::initialize(gtl::xml& node, wnd* parent_wnd)
{
	gtl::script* script = NULL;
	gtl::tstr type = node(_T("type"), true);
	if(type.icmp(_T("javascript")))
	{
		if(m_jscript == NULL)
		{
			m_jscript = new javascript;
			static_cast<javascript*>(m_jscript)->init();
		}

		script = m_jscript;
	}

	if(type.icmp(_T("python")))
	{
		if(m_pyscript == NULL)
		{
			m_pyscript = new pythonscript;
			static_cast<pythonscript*>(m_pyscript)->init();
		}

		script = m_pyscript;
	}

	gtl::tstr src = node.data();
	if(script != NULL)
	{
#ifdef UNICODE
		script->init(src.trans());
#else
		script->init(src);
#endif
	}

	return pane::initialize(node, parent_wnd);
}

bool script::eval(const gtl::str& src)
{
	if(m_jscript == NULL && m_pyscript == NULL)
		return false;

	gtl::str script_type;
	gtl::script* script = NULL;
	if(m_jscript != NULL && m_pyscript == NULL)
	{
		script = m_jscript;
	}
	else if(m_jscript == NULL && m_pyscript != NULL)
	{
		script = m_pyscript;
	}
	else if(src.icmp("javascript:", 11))
	{
		script_type = "javascript:";
		script = m_jscript;
	}
	else if(src.icmp("python:", 7))
	{
		script_type = "python:";
		script = m_pyscript;
	}
	else
	{
		script = m_jscript;
	}

	return script->eval(script_type.empty() ? src : gtl::str(src).ltrim(script_type));
}

bool script::call(const gtl::str& fun)
{
	if(m_jscript == NULL && m_pyscript == NULL)
		return false;
	
	gtl::script* script = NULL;
	if(m_jscript != NULL && m_pyscript == NULL)
		script = m_jscript;
	else if(m_jscript == NULL && m_pyscript != NULL)
		script = m_pyscript;
	else if(strncmp("javascript:", fun, 11) == 0)
		script = m_jscript;
	else if(strncmp("python:", fun, 7) == 0)
		script = m_pyscript;
	else
		script = m_jscript;
	
	return script->call(fun);
}

} // end of namespace skins

} // end of namespace gtl